//
//  FZCommonTool.m
//  EnglishTalk
//
//  Created by huyanming on 15/6/6.
//  Copyright (c) 2015年 Feizhu Tech. All rights reserved.
//
#define PI 3.1415926
#import "FZCommonTool.h"
#import <AdSupport/ASIdentifierManager.h>
#import "UIAlertView+SRBlocks.h"
#import "SRCellPhoneViewController.h"
#include <sys/param.h>
#import <AdSupport/AdSupport.h>
#include <sys/mount.h>

#import "RIButtonItem.h"


@implementation FZCommonTool

//计算两个经纬度之间的距离。
+(double) LantitudeLongitudeDist:(double)lon1 other_Lat:(double)lat1 self_Lon:(double)lon2 self_Lat:(double)lat2{
    double er = 6378137; // 6378700.0f;
    //ave. radius = 6371.315 (someone said more accurate is 6366.707)
    //equatorial radius = 6378.388
    //nautical mile = 1.15078
    double radlat1 = PI*lat1/180.0f;
    double radlat2 = PI*lat2/180.0f;
    //now long.
    double radlong1 = PI*lon1/180.0f;
    double radlong2 = PI*lon2/180.0f;
    if( radlat1 < 0 ) radlat1 = PI/2 + fabs(radlat1);// south
    if( radlat1 > 0 ) radlat1 = PI/2 - fabs(radlat1);// north
    if( radlong1 < 0 ) radlong1 = PI*2 - fabs(radlong1);//west
    if( radlat2 < 0 ) radlat2 = PI/2 + fabs(radlat2);// south
    if( radlat2 > 0 ) radlat2 = PI/2 - fabs(radlat2);// north
    if( radlong2 < 0 ) radlong2 = PI*2 - fabs(radlong2);// west
    //spherical coordinates x=r*cos(ag)sin(at), y=r*sin(ag)*sin(at), z=r*cos(at)
    //zero ag is up so reverse lat
    double x1 = er * cos(radlong1) * sin(radlat1);
    double y1 = er * sin(radlong1) * sin(radlat1);
    double z1 = er * cos(radlat1);
    double x2 = er * cos(radlong2) * sin(radlat2);
    double y2 = er * sin(radlong2) * sin(radlat2);
    double z2 = er * cos(radlat2);
    double d = sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)+(z1-z2)*(z1-z2));
    //side, side, side, law of cosines and arccos
    double theta = acos((er*er+er*er-d*d)/(2*er*er));
    double dist  = theta*er;
    return dist;
}

+ (NSString *)IDFAString
{
    NSBundle *adSupportBundle = [NSBundle bundleWithPath:@"/System/Library/Frameworks/AdSupport.framework"];
    [adSupportBundle load];
    
    if (adSupportBundle == nil) {
        return @"";
    }
    else{
        
        Class asIdentifierMClass = NSClassFromString(@"ASIdentifierManager");
        
        if(asIdentifierMClass == nil){
            return @"";
        }
        else{
            
            //for no arc
            //ASIdentifierManager *asIM = [[[asIdentifierMClass alloc] init] autorelease];
            //for arc
            ASIdentifierManager *asIM = [[asIdentifierMClass alloc] init];
            
            if (asIM == nil) {
                return @"";
            }
            else{
                
                if(asIM.advertisingTrackingEnabled){
                    return [asIM.advertisingIdentifier UUIDString];
                }
                else{
                    return [asIM.advertisingIdentifier UUIDString];
                }            }
        }
    }
}


/**
 *  绑定手机号码
 *  @param navigationController
 *  @param successBlock 绑定成功回调
 *  @param title 提示信息
 *  @param canleText 取消按钮标题
 *  @param okText  确定按钮标题
 */
+(void)bindCellPhoneWithSuccessBlock:(FZBindCellPhoneSuccessBlock)successBlock
                navigationController:(UINavigationController*)navigationController
                               title:(NSString*)title
                          cancleText:(NSString*)canleText
                              okText:(NSString*)okText{
    
    [[[UIAlertView alloc] initWithTitle:nil
                                message:title
                       cancelButtonItem:[RIButtonItem itemWithLabel:canleText action:^{
        
    }]
                       otherButtonItems:[RIButtonItem itemWithLabel:okText action:^{
        
        SRCellPhoneViewController * phoneVC=[[SRCellPhoneViewController alloc] init];
        phoneVC.hideCustomNavigationView = YES;
        phoneVC.hidesBottomBarWhenPushed = YES;
        phoneVC.title =@"绑定手机号码";
        phoneVC.successBlock = successBlock;
        navigationController.navigationBarHidden = NO;
        [navigationController pushViewController:phoneVC animated:YES];
    }], nil] show];
}


+(long long)freeSpace{
    struct statfs buf;
    long long freespace = -1;
    if(statfs("/var", &buf) >= 0){
        freespace = (long long)buf.f_bsize * buf.f_bfree;
    }
    return freespace;
}

+(float)getTotalDiskSpaceInBytes {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    struct statfs tStats;
    statfs([[paths lastObject] cString], &tStats);
    float totalSpace = (float)(tStats.f_blocks * tStats.f_bsize);
    return totalSpace;
}

+ (NSString *)getNoPrefixUserID:(NSString *)userID {
    if (!userID || userID.length <= 2) {
        return nil;
    }
    NSString *prefix = @"t";
    if ([userID hasPrefix:prefix]) {
        return [userID substringFromIndex:1];
    }
    prefix = @"u";
    if ([userID hasPrefix:prefix]) {
        return [userID substringFromIndex:1];
    }
    return userID;
}

+ (NSString *)addPrefixForUserID:(NSString *)userID prefix:(NSString *)prefix{
    if (!userID || userID.length <= 2 || !prefix) {
        return nil;
    }
    if (![userID hasPrefix:prefix]) {
        return [NSString stringWithFormat:@"%@%@", prefix, userID];
    }
    return userID;
}

#pragma mark -获得给定字符串的宽高

+ (CGRect)getRectwithString:(NSString *)string withFont:(CGFloat)font withWidth:(CGFloat)width
{
    CGRect rect=[string boundingRectWithSize:CGSizeMake(width, 1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:font]} context:nil];
    
    return rect;
}


+ (NSString *)dateToDetailDisplayStringForTimeInterval:(NSInteger)originTimeSince1970 {
    if (originTimeSince1970 <= 0) {
        return @"";
    }
    int selfSince1970 = (int)originTimeSince1970;
    int nowSince1970 = (int)[[NSDate date] timeIntervalSince1970];
    int yesterdaySince1970 = nowSince1970 - 60 * 60 * 24;
    int interval = nowSince1970 - selfSince1970;
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
    NSDateComponents *selfDateComponent = [calendar components:unitFlags fromDate:[NSDate dateWithTimeIntervalSince1970:selfSince1970]];
    NSDateComponents *nowDateComponent = [calendar components:unitFlags fromDate:[NSDate date]];
    NSDateComponents *yesterdayComponent = [calendar components:unitFlags fromDate:[NSDate dateWithTimeIntervalSince1970:yesterdaySince1970]];
    if (interval < 0) {
        return @"";
    } else if (interval <= 60) {
        // 60S及以内，显示“刚刚”
        return @"刚刚";
    } else if (interval <= 60 * 60) {
        // 60分钟及以内，显示“XX分钟前”
        return [NSString stringWithFormat:@"%d分钟前", (int)interval / 60];
    } else if ([selfDateComponent day] == [nowDateComponent day] && [selfDateComponent month] == [nowDateComponent month] && [selfDateComponent year] == [nowDateComponent year]) {
        // 今天，显示 几小时前
        return [NSString stringWithFormat:@"%d小时前", (int)interval / 3600];
    } else if ([selfDateComponent day] == [yesterdayComponent day] && [selfDateComponent month] == [yesterdayComponent month] && [selfDateComponent year] == [yesterdayComponent year]) {
        // 昨天，显示“昨天 HH:mm”
        NSDateFormatter *formater = [[NSDateFormatter alloc] init];
        formater.dateFormat = @"HH:mm";
        NSString *timeStr = [formater stringFromDate:[NSDate dateWithTimeIntervalSince1970:selfSince1970]];
        return [NSString stringWithFormat:@"昨天 %@", timeStr];
    } else if ([selfDateComponent year] == [nowDateComponent year]) {
        //显示“MM-dd HH:mm”
        NSDateFormatter *formater = [[NSDateFormatter alloc] init];
        formater.dateFormat = @"MM-dd HH:mm";
        return [formater stringFromDate:[NSDate dateWithTimeIntervalSince1970:selfSince1970]];
    } else {
        // 去年及以前，显示“yy-MM-dd HH:mm”
        NSDateFormatter *formater = [[NSDateFormatter alloc] init];
        formater.dateFormat = @"yy-MM-dd HH:mm";
        return [formater stringFromDate:[NSDate dateWithTimeIntervalSince1970:selfSince1970]];
        return [formater stringFromDate:[NSDate dateWithTimeIntervalSince1970:selfSince1970]];
    }
}
@end
